if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
    (function($) {
        $.fn.wordExport = function(fileName) {
            fileName = typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export";
            var xmls = "xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\"";
            var ss = "<!--[if gte mso 9]><xml>\n" +
                " <w:WordDocument>\n" +
                "  <w:View>Print</w:View>\n" +
                "  <w:GrammarState>Clean</w:GrammarState>\n" +
                "  <w:TrackMoves>false</w:TrackMoves>\n" +
                "  <w:TrackFormatting/>\n" +
                "  <w:ValidateAgainstSchemas/>\n" +
                "  <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>\n" +
                "  <w:IgnoreMixedContent>false</w:IgnoreMixedContent>\n" +
                "  <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>\n" +
                "  <w:DoNotPromoteQF/>\n" +
                "  <w:LidThemeOther>EN-US</w:LidThemeOther>\n" +
                "  <w:LidThemeAsian>ZH-CN</w:LidThemeAsian>\n" +
                "  <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript>\n" +
                "  <w:Compatibility>\n" +
                "   <w:BreakWrappedTables/>\n" +
                "   <w:SnapToGridInCell/>\n" +
                "   <w:WrapTextWithPunct/>\n" +
                "   <w:UseAsianBreakRules/>\n" +
                "   <w:DontGrowAutofit/>\n" +
                "   <w:SplitPgBreakAndParaMark/>\n" +
                "   <w:DontVertAlignCellWithSp/>\n" +
                "   <w:DontBreakConstrainedForcedTables/>\n" +
                "   <w:DontVertAlignInTxbx/>\n" +
                "   <w:Word11KerningPairs/>\n" +
                "   <w:CachedColBalance/>\n" +
                "   <w:UseFELayout/>\n" +
                "  </w:Compatibility>\n" +
                "  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>\n" +
                "  <m:mathPr>\n" +
                "   <m:mathFont m:val=\"Cambria Math\"/>\n" +
                "   <m:brkBin m:val=\"before\"/>\n" +
                "   <m:brkBinSub m:val=\"--\"/>\n" +
                "   <m:smallFrac m:val=\"off\"/>\n" +
                "   <m:dispDef/>\n" +
                "   <m:lMargin m:val=\"0\"/>\n" +
                "   <m:rMargin m:val=\"0\"/>\n" +
                "   <m:defJc m:val=\"centerGroup\"/>\n" +
                "   <m:wrapIndent m:val=\"1440\"/>\n" +
                "   <m:intLim m:val=\"subSup\"/>\n" +
                "   <m:naryLim m:val=\"undOvr\"/>\n" +
                "  </m:mathPr></w:WordDocument>\n" +
                "</xml><![endif]-->";
            var styles = " /* Font Definitions */\n" +
                " @font-face\n" +
                "\t{font-family:宋体;\n" +
                "\tpanose-1:2 1 6 0 3 1 1 1 1 1;\n" +
                "\tmso-font-alt:SimSun;\n" +
                "\tmso-font-charset:134;\n" +
                "\tmso-generic-font-family:auto;\n" +
                "\tmso-font-pitch:variable;\n" +
                "\tmso-font-signature:3 680460288 22 0 262145 0;}\n" +
                "@font-face\n" +
                "\t{font-family:\"Cambria Math\";\n" +
                "\tpanose-1:2 4 5 3 5 4 6 3 2 4;\n" +
                "\tmso-font-charset:1;\n" +
                "\tmso-generic-font-family:roman;\n" +
                "\tmso-font-format:other;\n" +
                "\tmso-font-pitch:variable;\n" +
                "\tmso-font-signature:0 0 0 0 0 0;}\n" +
                "@font-face\n" +
                "\t{font-family:\"\\@宋体\";\n" +
                "\tpanose-1:2 1 6 0 3 1 1 1 1 1;\n" +
                "\tmso-font-charset:134;\n" +
                "\tmso-generic-font-family:auto;\n" +
                "\tmso-font-pitch:variable;\n" +
                "\tmso-font-signature:3 680460288 22 0 262145 0;}\n" +
                " /* Style Definitions */\n" +
                " p.MsoNormal, li.MsoNormal, div.MsoNormal\n" +
                "\t{mso-style-unhide:no;\n" +
                "\tmso-style-qformat:yes;\n" +
                "\tmso-style-parent:\"\";\n" +
                "\tmargin:0cm;\n" +
                "\tmargin-bottom:.0001pt;\n" +
                "\tmso-pagination:widow-orphan;\n" +
                "\tfont-size:14.0pt;\n" +
                "\tfont-family:宋体;\n" +
                "\tmso-bidi-font-family:宋体;}\n" +
                "p.MsoHeader, li.MsoHeader, div.MsoHeader\n" +
                "\t{mso-style-noshow:yes;\n" +
                "\tmso-style-priority:99;\n" +
                "\tmso-style-link:\"页眉 Char\";\n" +
                "\tmargin:0cm;\n" +
                "\tmargin-bottom:.0001pt;\n" +
                "\ttext-align:center;\n" +
                "\tmso-pagination:widow-orphan;\n" +
                "\tlayout-grid-mode:char;\n" +
                "\tfont-size:9.0pt;\n" +
                "\tfont-family:宋体;\n" +
                "\tmso-bidi-font-family:宋体;}\n" +
                "p.MsoFooter, li.MsoFooter, div.MsoFooter\n" +
                "\t{mso-style-noshow:yes;\n" +
                "\tmso-style-priority:99;\n" +
                "\tmso-style-link:\"页脚 Char\";\n" +
                "\tmargin:0cm;\n" +
                "\tmargin-bottom:.0001pt;\n" +
                "\tmso-pagination:widow-orphan;\n" +
                "\tlayout-grid-mode:char;\n" +
                "\tfont-size:9.0pt;\n" +
                "\tfont-family:宋体;\n" +
                "\tmso-bidi-font-family:宋体;}\n" +
                "p.MsoAcetate, li.MsoAcetate, div.MsoAcetate\n" +
                "\t{mso-style-noshow:yes;\n" +
                "\tmso-style-priority:99;\n" +
                "\tmso-style-link:\"批注框文本 Char\";\n" +
                "\tmargin:0cm;\n" +
                "\tmargin-bottom:.0001pt;\n" +
                "\tmso-pagination:widow-orphan;\n" +
                "\tfont-size:9.0pt;\n" +
                "\tfont-family:宋体;\n" +
                "\tmso-bidi-font-family:宋体;}\n" +
                "span.Char\n" +
                "\t{mso-style-name:\"页眉 Char\";\n" +
                "\tmso-style-noshow:yes;\n" +
                "\tmso-style-priority:99;\n" +
                "\tmso-style-unhide:no;\n" +
                "\tmso-style-locked:yes;\n" +
                "\tmso-style-link:页眉;\n" +
                "\tfont-family:宋体;\n" +
                "\tmso-ascii-font-family:宋体;\n" +
                "\tmso-fareast-font-family:宋体;\n" +
                "\tmso-hansi-font-family:宋体;}\n" +
                "span.Char0\n" +
                "\t{mso-style-name:\"页脚 Char\";\n" +
                "\tmso-style-noshow:yes;\n" +
                "\tmso-style-priority:99;\n" +
                "\tmso-style-unhide:no;\n" +
                "\tmso-style-locked:yes;\n" +
                "\tmso-style-link:页脚;\n" +
                "\tfont-family:宋体;\n" +
                "\tmso-ascii-font-family:宋体;\n" +
                "\tmso-fareast-font-family:宋体;\n" +
                "\tmso-hansi-font-family:宋体;}\n" +
                "span.Char1\n" +
                "\t{mso-style-name:\"批注框文本 Char\";\n" +
                "\tmso-style-noshow:yes;\n" +
                "\tmso-style-priority:99;\n" +
                "\tmso-style-unhide:no;\n" +
                "\tmso-style-locked:yes;\n" +
                "\tmso-style-link:批注框文本;\n" +
                "\tfont-family:宋体;\n" +
                "\tmso-ascii-font-family:宋体;\n" +
                "\tmso-fareast-font-family:宋体;\n" +
                "\tmso-hansi-font-family:宋体;}\n" +
                "p.msochpdefault, li.msochpdefault, div.msochpdefault\n" +
                "\t{mso-style-name:msochpdefault;\n" +
                "\tmso-style-unhide:no;\n" +
                "\tmso-margin-top-alt:auto;\n" +
                "\tmargin-right:0cm;\n" +
                "\tmso-margin-bottom-alt:auto;\n" +
                "\tmargin-left:0cm;\n" +
                "\tmso-pagination:widow-orphan;\n" +
                "\tfont-size:10.0pt;\n" +
                "\tfont-family:宋体;\n" +
                "\tmso-bidi-font-family:宋体;}\n" +
                "span.msonormal0\n" +
                "\t{mso-style-name:msonormal;\n" +
                "\tmso-style-unhide:no;}\n" +
                ".MsoChpDefault\n" +
                "\t{mso-style-type:export-only;\n" +
                "\tmso-default-props:yes;\n" +
                "\tfont-size:10.0pt;\n" +
                "\tmso-ansi-font-size:10.0pt;\n" +
                "\tmso-bidi-font-size:10.0pt;\n" +
                "\tmso-ascii-font-family:\"Times New Roman\";\n" +
                "\tmso-hansi-font-family:\"Times New Roman\";\n" +
                "\tmso-font-kerning:0pt;}\n" +
                " /* Page Definitions */\n" +
                "@page WordSection1\n" +
                "\t{size:595.3pt 841.9pt;\n" +
                "\tmargin:72.0pt 90.0pt 72.0pt 90.0pt;\n" +
                "\tmso-header-margin:42.55pt;\n" +
                "\tmso-footer-margin:49.6pt;\n" +
                "\tmso-paper-source:0;}\n" +
                "div.WordSection1\n" +
                "\{page:WordSection1;}\n";
            var static = {
                mhtml: {
                    top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n<!DOCTYPE html>\n<html "+ xmls +">\n_html_</html>",
                    head: "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"+ss+" <style>\n_styles_\n</style>\n</head>\n",
                    body: "<body>_body_</body>"
                }
            };
            var options = {
                maxWidth: 624
            };
            // Clone selected element before manipulating it
            var markup = $(this).clone();

            // Remove hidden elements from the output
            markup.each(function() {
                var self = $(this);
                if (self.is(':hidden'))
                    self.remove();
            });

            // Embed all images using Data URLs
            var images = Array();
            // var img = markup.find('img');
            var img = img = new Image();
            for (var i = 0; i < img.length; i++) {
                // Calculate dimensions of output image
                var w = Math.min(img[i].width, options.maxWidth);
                var h = img[i].height * (w / img[i].width);
                // Create canvas for converting image to data URL
                var canvas = document.createElement("CANVAS");
                canvas.width = w;
                canvas.height = h;
                // Draw image to canvas
                var context = canvas.getContext('2d');
                context.drawImage(img[i], 0, 0, w, h);
                // Get data URL encoding of image
                var uri = canvas.toDataURL("image/png");
                $(img[i]).attr("src", img[i].src);
                img[i].width = w;
                img[i].height = h;
                // Save encoded image to array
                images[i] = {
                    type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
                    encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
                    location: $(img[i]).attr("src"),
                    data: uri.substring(uri.indexOf(",") + 1)
                };
            }

            // Prepare bottom of mhtml file with image data
            var mhtmlBottom = "\n";
            for (var i = 0; i < images.length; i++) {
                mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n";
                mhtmlBottom += "Content-Location: " + images[i].location + "\n";
                mhtmlBottom += "Content-Type: " + images[i].type + "\n";
                mhtmlBottom += "Content-Transfer-Encoding: " + images[i].encoding + "\n\n";
                mhtmlBottom += images[i].data + "\n\n";
            }
            mhtmlBottom += "--NEXT.ITEM-BOUNDARY--";

            //TODO: load css from included stylesheet
            // var styles = "";

            // Aggregate parts of the file together
            var fileContent = static.mhtml.top.replace("_html_", static.mhtml.head.replace("_styles_", styles) + static.mhtml.body.replace("_body_", markup.html())) + mhtmlBottom;

            // Create a Blob with the file contents
            var blob = new Blob([fileContent], {
                type: "application/msword;charset=utf-8"
            });
            saveAs(blob, fileName + ".doc");
        };
    })(jQuery);
} else {
    if (typeof jQuery === "undefined") {
        console.error("jQuery Word Export: missing dependency (jQuery)");
    }
    if (typeof saveAs === "undefined") {
        console.error("jQuery Word Export: missing dependency (FileSaver.js)");
    }
}
